﻿using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using Facebook;
using EsaProjectRest.Service;
using System.Collections.Generic;
using System.Dynamic;
using Twitterizer;

namespace EsaProjectRest.Twitter
{
    public class PostTW
    {
        private const String CONSUMER_KEY = "RUMoRPLvEHqN9dPoFIiwQ";  // old :  "NxCOfv9GUBLxXCGaAgYQQ";
        private const String CONSUMER_SECRET = "krqcrLoTxiG3cudESjArlpxAMbnfvkbf77ic9MyyE";  // old :  "lLt60LIinqbm2LAhxNpxUdAwOoO1AJu3xXdcSuFQXRo";


        public Boolean UpdateMyPostTW(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();


            try
            {
                service1.OpenConnection();
                char[] delimiter = { ';' };
                string Token = services.ReadToken(id, "Twitter");
                string[] TokenSplit = Token.Split(delimiter);
                string accessToken = TokenSplit[0];
                string accessTokenSecret = TokenSplit[1];

                string mypost;
                string date;
                string condivisioni;
                OAuthTokens tokens = new OAuthTokens();


                tokens.ConsumerKey = CONSUMER_KEY;
                tokens.ConsumerSecret = CONSUMER_SECRET;
                tokens.AccessToken = accessToken;
                tokens.AccessTokenSecret = accessTokenSecret;

                TwitterResponse<TwitterStatusCollection> timelineResponse = TwitterTimeline.UserTimeline(tokens);

                char[] split = { ' ' };
                char[] split2 = { '/' };
                char[] split3 = { ':' }; // origniariamente '.'


                int month_attuale = (int)System.DateTime.Now.Month - 1;
                int day_attuale = (int)System.DateTime.Now.Day;

                foreach (TwitterStatus status in timelineResponse.ResponseObject)
                {
                    if (status.Text != null)
                    {
                        mypost = status.Text.ToString();
                        string[] data = status.CreatedDate.ToString().Split(split);
                        string[] date_err = data[0].Split(split2);
                        string giorno = date_err[0];
                        string mese = date_err[1];
                        string anno = date_err[2];
                        string[] time_err = data[1].Split(split3);
                        string ora = time_err[0];
                        string minuti = time_err[1];
                        string secondi = time_err[2];
                        date = anno + "-" + mese + "-" + giorno + " " + ora + ":" + minuti + ":" + secondi;
                        date = DateTimeConvertor.ToIso8601FormattedDateTime(Convert.ToDateTime(date));
                        condivisioni = status.RetweetCount.ToString();

                        if ((int.Parse(giorno) <= day_attuale && int.Parse(mese) == month_attuale + 1) || (int.Parse(giorno) >= day_attuale && int.Parse(mese) == month_attuale))
                        {
                            System.Diagnostics.Debug.Print("Mese: " + mese + " Giorno" + giorno);
                            DataSet vds = new DataSet();
                            string vsql = string.Format("SELECT Id FROM [Post] WHERE (Id_user = '" + id + "') and (Message = '" + HttpUtility.HtmlEncode(mypost) + "') and (Date = '" + date + "') and (SocialNetwork = 'Twitter')");
                            SqlCommand vCom = new SqlCommand(vsql, service1.conn);
                            SqlDataAdapter vda = new SqlDataAdapter(vCom);
                            vda.Fill(vds);

                            try
                            {
                                //memorize id
                                string id_post = vds.Tables[0].Rows[0]["Id"].ToString();
                                //System.Diagnostics.Debug.Print("Id_post: " + id_post);
                                vda.Dispose();
                                string sql2 = string.Format("UPDATE [Post] SET N_Shares='" + condivisioni + "' WHERE (Id = '" + id_post + "') ");
                                SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                                com2.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                System.Console.WriteLine(ex.Message);
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            return true;
        }
        private Boolean MyPostsTWPrime(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();
            try
            {
                service1.OpenConnection();
                char[] delimiter = { ';' };
                string Token = services.ReadToken(id, "Twitter");
                string[] TokenSplit = Token.Split(delimiter);
                string accessToken = TokenSplit[0];
                string accessTokenSecret = TokenSplit[1];

                string[] mypost = new string[20];
                string[] date = new string[20];
                string[] condivisioni = new string[20];
                OAuthTokens tokens = new OAuthTokens();
                int i = 0;
                int count = 0;


                tokens.ConsumerKey = CONSUMER_KEY;
                tokens.ConsumerSecret = CONSUMER_SECRET;
                tokens.AccessToken = accessToken;
                tokens.AccessTokenSecret = accessTokenSecret;

                TwitterResponse<TwitterStatusCollection> timelineResponse = TwitterTimeline.UserTimeline(tokens);

                char[] split = { ' ' };
                char[] split2 = { '/' };
                char[] split3 = { ':' }; // origniariamente '.'


                foreach (TwitterStatus status in timelineResponse.ResponseObject)
                {
                    if (status.Text != null)
                    {
                        mypost[i] = status.Text.ToString();
                        string[] data = status.CreatedDate.ToString().Split(split);
                        string[] date_err = data[0].Split(split2);
                        string giorno = date_err[0];
                        string mese = date_err[1];
                        string anno = date_err[2];
                        string[] time_err = data[1].Split(split3);
                        string ora = time_err[0];
                        string minuti = time_err[1];
                        string secondi = time_err[2];
                        date[i] = anno + "-" + mese + "-" + giorno + " " + ora + ":" + minuti + ":" + secondi;
                        date[i] = DateTimeConvertor.ToIso8601FormattedDateTime(Convert.ToDateTime(date[i]));
                        condivisioni[i] = status.RetweetCount.ToString();
                        i++;
                        count++;
                    }

                }
                for (int j = count - 1; j >= 0; j--)
                {
                    //System.Diagnostics.Debug.Print("for: "+mypost[j]);
                    if (mypost[j] != null)
                    {
                        string sql2 = string.Format("INSERT INTO [Post](Id_user,Message,Date,SocialNetwork,N_Likes,N_Comments,N_Shares) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", id, HttpUtility.HtmlEncode(mypost[j]), date[j], "Twitter", 0, 0, int.Parse(condivisioni[j]));
                        //System.Diagnostics.Debug.Print("sql: " + sql2);
                        SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                        com2.ExecuteNonQuery();
                    }
                }

                //System.Diagnostics.Debug.Print(i.ToString());
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore TW prime");
                service1.CloseConnection();
                return false;
            }
        }

        public Boolean MyPostsTW(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();

            try
            {
                service1.OpenConnection();
                try
                {
                    //System.Diagnostics.Debug.Print("Ciao");
                    DataSet vds = new DataSet();
                    string sql = string.Format("SELECT Id_user,Message,Date FROM [Post] WHERE (Id_user = '" + id + "') and (SocialNetwork = 'Twitter') ORDER BY Id DESC");
                    SqlCommand vCom = new SqlCommand(sql, service1.conn);
                    SqlDataAdapter vda = new SqlDataAdapter(vCom);
                    vda.Fill(vds);
                    string message_user = vds.Tables[0].Rows[0]["Message"].ToString();
                    string date_user = vds.Tables[0].Rows[0]["Date"].ToString();
                    //System.Diagnostics.Debug.Print(message_user);

                    vda.Dispose();

                    char[] delimiter = { ';' };
                    string Token = services.ReadToken(id, "Twitter");
                    string[] TokenSplit = Token.Split(delimiter);
                    string accessToken = TokenSplit[0];
                    string accessTokenSecret = TokenSplit[1];

                    string[] mypost = new string[20];
                    string[] date = new string[20];
                    string[] condivisioni = new string[20];
                    OAuthTokens tokens = new OAuthTokens();
                    int i = 0;
                    int count = 0;
                    int[] tot_comments = new int[20];
                    char[] split = { ' ' };
                    char[] split2 = { '/' };
                    char[] split3 = { ':' };  // delimitatore originario ':'


                    tokens.ConsumerKey = CONSUMER_KEY;
                    tokens.ConsumerSecret = CONSUMER_SECRET;




                    tokens.AccessToken = accessToken;
                    tokens.AccessTokenSecret = accessTokenSecret;
                    //System.Diagnostics.Debug.Print("Ciao");
                    TwitterResponse<TwitterStatusCollection> timelineResponse = TwitterTimeline.UserTimeline(tokens);
                    TwitterResponse<TwitterStatusCollection> mention = TwitterTimeline.Mentions(tokens);

                    foreach (TwitterStatus status in timelineResponse.ResponseObject)
                    {
                        // System.Diagnostics.Debug.Print(status.User + ": " + status.Text);
                        if (status.Text != null)
                        {
                            mypost[i] = status.Text.ToString();
                            string[] data = status.CreatedDate.ToString().Split(split);
                            string[] date_err = data[0].Split(split2);
                            string giorno = date_err[0];
                            string mese = date_err[1];
                            string anno = date_err[2];
                            string[] time_err = data[1].Split(split3);
                            string ora = time_err[0];
                            string minuti = time_err[1];
                            string secondi = time_err[2];
                            date[i] = anno + "-" + mese + "-" + giorno + " " + ora + ":" + minuti + ":" + secondi;
                            date[i] = DateTimeConvertor.ToIso8601FormattedDateTime(Convert.ToDateTime(date[i]));
                            condivisioni[i] = status.RetweetCount.ToString();
                            i++;
                            count++;
                        }
                    }

                    //System.Diagnostics.Debug.Print("message user: "+message_user);

                    for (int j = 0; j < count; j++)
                    {
                        //System.Diagnostics.Debug.Print("message user2: " + mypost[j]);
                        if ((HttpUtility.HtmlEncode(mypost[j]) != message_user) && (date[j] != date_user))
                        {
                            string sql2 = string.Format("INSERT INTO [Post](Id_user,Message,Date,SocialNetwork,N_Likes,N_Comments,N_Shares) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", id, HttpUtility.HtmlEncode(mypost[j]), date[j], "Twitter", 0, 0, int.Parse(condivisioni[j]));
                            SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                            com2.ExecuteNonQuery();
                        }
                        else
                        {
                            j = count + 1;
                        }
                    }

                }
                catch (Exception ex)
                {
                    //System.Diagnostics.Debug.Print("errore 11111");
                    System.Console.WriteLine(ex.Message);
                    System.Diagnostics.Debug.Print("Chiamo TW prime");
                    Boolean ris = MyPostsTWPrime(id);
                }
                service1.CloseConnection();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore TW");
                service1.CloseConnection();
                return false;
            }

        }

        private Boolean MyTagsTWPrime(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();
            try
            {
                service1.OpenConnection();
                char[] delimiter = { ';' };
                string Token = services.ReadToken(id, "Twitter");
                string[] TokenSplit = Token.Split(delimiter);
                string accessToken = TokenSplit[0];
                string accessTokenSecret = TokenSplit[1];

                string[] tag = new string[20];
                string[] img_tag = new string[20];
                string[] mypost = new string[20];
                string[] date = new string[20];
                OAuthTokens tokens = new OAuthTokens();
                int i = 0;
                int count = 0;


                tokens.ConsumerKey = CONSUMER_KEY;
                tokens.ConsumerSecret = CONSUMER_SECRET;
                tokens.AccessToken = accessToken;
                tokens.AccessTokenSecret = accessTokenSecret;

                TwitterResponse<TwitterStatusCollection> mention = TwitterTimeline.Mentions(tokens);

                char[] split = { ' ' };
                char[] split2 = { '/' };
                char[] split3 = { ':' }; // origniariamente '.'


                foreach (TwitterStatus status in mention.ResponseObject)
                {
                    if (status.Text != null)
                    {
                        tag[i] = status.User.ScreenName.ToString();
                        img_tag[i] = status.User.ProfileImageLocation.ToString();
                        mypost[i] = status.Text.ToString();

                        string[] data = status.CreatedDate.ToString().Split(split);
                        string[] date_err = data[0].Split(split2);
                        string giorno = date_err[0];
                        string mese = date_err[1];
                        string anno = date_err[2];
                        string[] time_err = data[1].Split(split3);
                        string ora = time_err[0];
                        string minuti = time_err[1];
                        string secondi = time_err[2];
                        date[i] = anno + "-" + mese + "-" + giorno + " " + ora + ":" + minuti + ":" + secondi;
                        date[i] = DateTimeConvertor.ToIso8601FormattedDateTime(Convert.ToDateTime(date[i]));
                        i++;
                        count++;

                    }

                }
                for (int j = count - 1; j >= 0; j--)
                {
                    if (mypost[j] != null)
                    {
                        string sql2 = string.Format("INSERT INTO [TagPost](Id_user,Tag,Message,Date,SocialNetwork,Img_Tag) values('{0}','{1}','{2}','{3}','{4}','{5}')", id, tag[j], HttpUtility.HtmlEncode(mypost[j]), date[j], "Twitter", img_tag[j]);
                        System.Diagnostics.Debug.Print("sql: " + sql2);
                        SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                        com2.ExecuteNonQuery();
                    }
                }

                //System.Diagnostics.Debug.Print(i.ToString());
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore TW prime");
                service1.CloseConnection();
                return false;
            }
        }

        public Boolean MyTagsTW(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();

            try
            {
                service1.OpenConnection();
                try
                {
                    //System.Diagnostics.Debug.Print("Ciao");
                    DataSet vds = new DataSet();
                    string sql = string.Format("SELECT Id_user,Message,Date FROM [TagPost] WHERE (Id_user = '" + id + "') and (SocialNetwork = 'Twitter') ORDER BY Id DESC");
                    //System.Diagnostics.Debug.Print(sql);
                    SqlCommand vCom = new SqlCommand(sql, service1.conn);
                    SqlDataAdapter vda = new SqlDataAdapter(vCom);
                    vda.Fill(vds);
                    string message_user = vds.Tables[0].Rows[0]["Message"].ToString();
                    string date_user = vds.Tables[0].Rows[0]["Date"].ToString();

                    vda.Dispose();

                    char[] delimiter = { ';' };
                    string Token = services.ReadToken(id, "Twitter");
                    string[] TokenSplit = Token.Split(delimiter);
                    string accessToken = TokenSplit[0];
                    string accessTokenSecret = TokenSplit[1];

                    string[] tag = new string[20];
                    string[] img_tag = new string[20];
                    string[] mypost = new string[20];
                    string[] date = new string[20];
                    string[] image_post = new string[20];
                    OAuthTokens tokens = new OAuthTokens();
                    int i = 0;
                    int count = 0;
                    char[] split = { ' ' };
                    char[] split2 = { '/' };
                    char[] split3 = { ':' }; // origniariamente '.'



                    tokens.ConsumerKey = CONSUMER_KEY;
                    tokens.ConsumerSecret = CONSUMER_SECRET;
                    tokens.AccessToken = accessToken;
                    tokens.AccessTokenSecret = accessTokenSecret;
                    //System.Diagnostics.Debug.Print("Ciao");
                    TwitterResponse<TwitterStatusCollection> mentions = TwitterTimeline.Mentions(tokens);

                    foreach (TwitterStatus status in mentions.ResponseObject)
                    {
                        // System.Diagnostics.Debug.Print(status.User + ": " + status.Text);
                        if (status.Text != null)
                        {
                            tag[i] = status.User.ScreenName.ToString();
                            img_tag[i] = status.User.ProfileImageLocation.ToString();
                            mypost[i] = status.Text.ToString();

                            string[] data = status.CreatedDate.ToString().Split(split);
                            string[] date_err = data[0].Split(split2);
                            string giorno = date_err[0];
                            string mese = date_err[1];
                            string anno = date_err[2];
                            string[] time_err = data[1].Split(split3);
                            string ora = time_err[0];
                            string minuti = time_err[1];
                            string secondi = time_err[2];
                            date[i] = anno + "-" + mese + "-" + giorno + " " + ora + ":" + minuti + ":" + secondi;
                            date[i] = DateTimeConvertor.ToIso8601FormattedDateTime(Convert.ToDateTime(date[i]));
                            i++;
                            count++;
                        }

                    }

                    //System.Diagnostics.Debug.Print("message user: "+message_user);

                    for (int j = 0; j < count; j++)
                    {
                        //System.Diagnostics.Debug.Print("message user2: " + mypost[j]);
                        if ((HttpUtility.HtmlEncode(mypost[j]) != message_user) && (date[j] != date_user))
                        {
                            string sql2 = string.Format("INSERT INTO [TagPost](Id_user,Tag,Message,Date,SocialNetwork,Img_Tag) values('{0}','{1}','{2}','{3}','{4}','{5}')", id, tag[j], HttpUtility.HtmlEncode(mypost[j]), date[j], "Twitter", img_tag[j]);
                            SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                            com2.ExecuteNonQuery();
                        }
                        else
                        {
                            j = count + 1;
                        }
                    }

                }
                catch (Exception ex)
                {
                    //System.Diagnostics.Debug.Print("errore 11111");
                    System.Console.WriteLine(ex.Message);
                    System.Diagnostics.Debug.Print("Chiamo TW prime");
                    Boolean ris = MyTagsTWPrime(id);
                }
                service1.CloseConnection();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore TW");
                service1.CloseConnection();
                return false;
            }

        }

        public Boolean CrossPostingTW(string id, string message)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();

            try
            {
                service1.OpenConnection();
                try
                {
                    char[] delimiter = { ';' };
                    string Token = services.ReadToken(id, "Twitter");
                    string[] TokenSplit = Token.Split(delimiter);
                    string accessToken = TokenSplit[0];
                    string accessTokenSecret = TokenSplit[1];

                    OAuthTokens tokens = new OAuthTokens();

                    tokens.ConsumerKey = CONSUMER_KEY;
                    tokens.ConsumerSecret = CONSUMER_SECRET;
                    tokens.AccessToken = accessToken;
                    tokens.AccessTokenSecret = accessTokenSecret;

                    TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, message);

                    if (tweetResponse.Result == RequestResult.Success)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                    System.Diagnostics.Debug.Print("Errore nel cross posting di TW");
                    Boolean ris = MyTagsTWPrime(id);
                    return false;
                }
                service1.CloseConnection();
                //return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore TW");
                service1.CloseConnection();
                return false;
            }
        }

    }
}
